﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using com.youzu.warh.protocol;
using Yoozoo.External.LZ4;
using UnityEngine;
using Yoozoo.Gameplay.RTS;
using Yoozoo.Gta.Common;
using Yoozoo.Libs;

public class RpgReportManager
{
    private ReportRequester reportRequester;

    private static RpgReportManager instance;
    
    public static RpgReportManager Instance
    {
        get
        {
            if (instance == null)
            {
                instance = new RpgReportManager();
            }
            return instance;
        }
    }
    
    public void Initialize()
    {
        reportRequester = new ReportRequester();
        reportRequester.Initialize();
        reportRequester.SetHandler(DeserializeReport,OnGetReport,OnGetReportFailed);
    }

    public void Update()
    {
        reportRequester?.Update();
    }
    
    public void RequestReport(string url)
    {
        reportRequester.RequestReport(url);
    }
    
    [Serializable]
    private class ReportFile
    {
        public string data;
        public int status;
    }


    private byte[] DeserializeReport(byte[] message)
    {
        var jsonString = Encoding.UTF8.GetString(message);
            var reportFile = JsonUtility.FromJson<ReportFile>(jsonString);
            if (reportFile == null)
            {
                Debug.LogError("[RPG竞技场]战报Json解析错误");
                return null;
            }

            if (reportFile.status != 0)
            {
                Debug.LogError("[RPG竞技场]战报请求出错，status = " + reportFile.status);
                return null;
            }

            if (reportFile.data == null)
            {
                Debug.LogError("[RPG竞技场]战报data为空："+jsonString);
                return null;
            }
            var data = Convert.FromBase64String(reportFile.data);
            try
            {
                int decodeLen = Converter.GetBigEndian(BitConverter.ToInt32(data, 0));
                var msgLen = data.Length - 4;
                byte[] proto = null;
                if (decodeLen == 0)
                {
                    int protoLen = msgLen;
                    proto = new byte[protoLen];
                    Array.Copy(data, 4, proto, 0, protoLen);
                }
                else
                {
                    int decodeLength = msgLen;
                    byte[] outPutBytes = new byte[decodeLen];
                    if (LZ4Codec.Decode(data, 4, decodeLength, outPutBytes, 0,
                            decodeLen) == decodeLen)
                    {
                        proto = outPutBytes;
                    }
                    else
                    {
                        UnityEngine.Debug.LogErrorFormat("<color=red> LZ4Codec.Decode failed!!!</color>");
                    }
                }

                if (proto != null)
                {
                    return proto;
                }
            }
            catch (Exception e)
            {
                Debug.LogError("[RTS竞技场]战报Proto解析过程中报错:\n"+reportFile.data);
                Debug.LogError(e.ToString());
#if UNITY_EDITOR
                /*FileStream fs = new FileStream(System.Environment.CurrentDirectory  + "/Caches/ERROR_" + reportId + ".txt", FileMode.Create);
                fs.Write(Encoding.UTF8.GetBytes(jsonString), 0, jsonString.Length);
                fs.Close();*/
#endif
            }
            return null;
    }
    
    private void OnGetReport(object data)
    {
        ResidentHandler.Inst.GetFunction("L_RpgReportManager.DeserializeProtoData").Action(data);
    }

    private void OnGetReportFailed(bool timeout = false)
    {
        Debug.LogError("战报获取失败");
        ResidentHandler.Inst.GetFunction("L_RpgReportManager.GetReportFailed").Action();
    }
}
